package com.easyjop.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.easyjop.entity.constants.Constants;
import com.easyjop.entity.dto.AppUserLoginDto;
import com.easyjop.entity.enums.UserStatusEnum;
import com.easyjop.exception.BusinessException;
import com.easyjop.utils.JWTUtil;
import org.springframework.stereotype.Service;

import com.easyjop.entity.enums.PageSize;
import com.easyjop.entity.query.AppUserInfoQuery;
import com.easyjop.entity.po.AppUserInfo;
import com.easyjop.entity.vo.PaginationResultVO;
import com.easyjop.entity.query.SimplePage;
import com.easyjop.mappers.AppUserInfoMapper;
import com.easyjop.service.AppUserInfoService;
import com.easyjop.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;


/**
 *  业务接口实现
 */
@Service("appUserInfoService")
public class AppUserInfoServiceImpl implements AppUserInfoService {

	@Resource
	private AppUserInfoMapper<AppUserInfo, AppUserInfoQuery> appUserInfoMapper;
	@Resource
	private JWTUtil<AppUserLoginDto> jwtUtil;


	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<AppUserInfo> findListByParam(AppUserInfoQuery param) {
		return this.appUserInfoMapper.selectList(param);
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(AppUserInfoQuery param) {
		return this.appUserInfoMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<AppUserInfo> findListByPage(AppUserInfoQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<AppUserInfo> list = this.findListByParam(param);
		PaginationResultVO<AppUserInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(AppUserInfo bean) {
		return this.appUserInfoMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<AppUserInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUserInfoMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<AppUserInfo> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUserInfoMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(AppUserInfo bean, AppUserInfoQuery param) {
		StringTools.checkParam(param);
		return this.appUserInfoMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(AppUserInfoQuery param) {
		StringTools.checkParam(param);
		return this.appUserInfoMapper.deleteByParam(param);
	}

	/**
	 * 根据UserId获取对象
	 */
	@Override
	public AppUserInfo getAppUserInfoByUserId(String userId) {
		return this.appUserInfoMapper.selectByUserId(userId);
	}

	/**
	 * 根据UserId修改
	 */
	@Override
	public Integer updateAppUserInfoByUserId(AppUserInfo bean, String userId) {
		return this.appUserInfoMapper.updateByUserId(bean, userId);
	}

	/**
	 * 根据UserId删除
	 */
	@Override
	public Integer deleteAppUserInfoByUserId(String userId) {
		return this.appUserInfoMapper.deleteByUserId(userId);
	}

	/**
	 * 根据Email获取对象
	 */
	@Override
	public AppUserInfo getAppUserInfoByEmail(String email) {
		return this.appUserInfoMapper.selectByEmail(email);
	}

	/**
	 * 根据Email修改
	 */
	@Override
	public Integer updateAppUserInfoByEmail(AppUserInfo bean, String email) {
		return this.appUserInfoMapper.updateByEmail(bean, email);
	}

	/**
	 * 根据Email删除
	 */
	@Override
	public Integer deleteAppUserInfoByEmail(String email) {
		return this.appUserInfoMapper.deleteByEmail(email);
	}

	@Override
	public void regiser(AppUserInfo appUserInfo) {
		appUserInfo.setJoinTime(new Date());
		appUserInfo.setLastLoginTime(new Date());
		AppUserInfo appUserInfo1 = this.appUserInfoMapper.selectByEmail(appUserInfo.getEmail());
		if (appUserInfo1!=null){
			throw new BusinessException("邮箱已存在");
		}
		AppUserInfoQuery appUserInfoQuery = new AppUserInfoQuery();
		appUserInfoQuery.setNickName(appUserInfo.getNickName());
		Integer integer = this.appUserInfoMapper.selectCount(appUserInfoQuery);
		if (integer>0){
			throw new RuntimeException("昵称已存在");
		}
		appUserInfo.setUserId(StringTools.getRandomNumber(10));
		appUserInfo.setPassword(StringTools.encodeByMD5(appUserInfo.getPassword()));
		appUserInfo.setStatus(UserStatusEnum.ENABLE.getStatus());
		this.appUserInfoMapper.insert(appUserInfo);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String login(String email, String password, String ipAddr, String deviceId, String deviceBrand) {
		AppUserInfo byEmail = this.appUserInfoMapper.selectByEmail(email);
		if (byEmail==null){
			throw new BusinessException("邮箱不存在,请注册");
		}
		if (!byEmail.getPassword().equals(password)){
			throw new BusinessException("账号或密码错误");
		}
		if (UserStatusEnum.DISABLE.equals(byEmail.getStatus())){
			throw new BusinessException("账号已被禁用");
		}
		byEmail.setLastLoginIp(ipAddr);
		byEmail.setLastUseDeviceId(deviceId);
		byEmail.setLastUseDeviceBrand(deviceBrand);
		byEmail.setLastLoginTime(new Date());
		/*更新*/
		this.appUserInfoMapper.updateByUserId(byEmail,byEmail.getUserId());
		AppUserLoginDto loginDto = new AppUserLoginDto();
		loginDto.setUserId(byEmail.getUserId());
		loginDto.setNickName(byEmail.getNickName());
		String token = jwtUtil.createToken(Constants.JWT_KEY_LOGIN_TOKEN, loginDto, Constants.JWT_TOKEN_EXPIRES_DAYS);
		return token;

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String autoLogin(String token, String deviceId, String deviceBrand, String ipAddr) {
		AppUserLoginDto tokenData = jwtUtil.getTokenData(Constants.JWT_KEY_LOGIN_TOKEN, token, AppUserLoginDto.class);
		if (tokenData==null){
			return null;
		}
		AppUserInfo appUserInfo = appUserInfoMapper.selectByUserId(tokenData.getUserId());
		if (null == appUserInfo || !UserStatusEnum.ENABLE.getStatus().equals(appUserInfo.getStatus())) {
			return null;
		}
		AppUserInfo updateInfo = new AppUserInfo();
		updateInfo.setLastLoginTime(new Date());
		updateInfo.setLastLoginIp(ipAddr);
		updateInfo.setLastUseDeviceId(deviceId);
		updateInfo.setLastUseDeviceBrand(deviceBrand);
		this.appUserInfoMapper.updateByUserId(updateInfo, tokenData.getUserId());

		String newToken = jwtUtil.createToken(Constants.JWT_KEY_LOGIN_TOKEN, tokenData, Constants.JWT_TOKEN_EXPIRES_DAYS);
		return newToken;
	}
}